import tkinter as tk
from tkinter import ttk, messagebox

class PlaceholderEntry(ttk.Entry):
    """带placeholder功能的自定义输入框组件"""

    def __init__(self, parent, placeholder_text="", placeholder_color="grey",
                 normal_color="black", *args, **kwargs):
        super().__init__(parent, *args, **kwargs)

        self.placeholder_text = placeholder_text
        self.placeholder_color = placeholder_color
        self.normal_color = normal_color
        self.is_placeholder = True

        # 设置初始placeholder
        self.insert(0, self.placeholder_text)
        self.config(foreground=self.placeholder_color)

        # 绑定事件
        self.bind("<FocusIn>", self._on_focus_in)
        self.bind("<FocusOut>", self._on_focus_out)

    def _on_focus_in(self, event):
        """获得焦点时清除placeholder"""
        if self.is_placeholder:
            self.delete(0, tk.END)
            self.config(foreground=self.normal_color)
            self.is_placeholder = False

    def _on_focus_out(self, event):
        """失去焦点时，如果内容为空则恢复placeholder"""
        if not self.get():
            self.insert(0, self.placeholder_text)
            self.config(foreground=self.placeholder_color)
            self.is_placeholder = True

    def get_content(self):
        """获取真实内容（如果是placeholder则返回空字符串）"""
        if self.is_placeholder:
            return ""
        return self.get()

    def set_placeholder(self, text=None):
        """动态设置placeholder文本"""
        if text is not None:
            self.placeholder_text = text

        # 如果当前是placeholder状态，更新文本
        if self.is_placeholder:
            self.delete(0, tk.END)
            self.insert(0, self.placeholder_text)

    def clear(self, show_placeholder=True):
        """清空输入框"""
        self.delete(0, tk.END)
        if show_placeholder:
            self.insert(0, self.placeholder_text)
            self.config(foreground=self.placeholder_color)
            self.is_placeholder = True
        else:
            self.config(foreground=self.normal_color)
            self.is_placeholder = False


